@model ThridGroup.ERP.DTO.OrderManagement.SalesOrderDto
@{
    ViewData["Title"] = Model.Id > 0 ? "编辑销售订单" : "新增销售订单";
    Layout = null;
}

<!-- 引入所需的CSS和JS文件 -->
<link href="~/libs/scripts/layui-v2.5.6/layui/css/layui.css" rel="stylesheet" />
<script src="~/libs/jquery/jquery.js"></script>
<script src="~/libs/scripts/layui-v2.5.6/layui/layui.js"></script>

<!-- 自定义样式 -->
<style>
    body {
        background: #f4f6fa;
        font-family: 'Segoe UI', 'Microsoft YaHei', Arial, sans-serif;
    }
    .edit-container {
        padding: 30px 0;
        background-color: #f4f6fa;
        min-height: 100vh;
    }
    .edit-card {
        background: #fff;
        border-radius: 12px;
        box-shadow: 0 4px 24px rgba(30, 159, 255, 0.08), 0 1.5px 6px rgba(0,0,0,0.03);
        overflow: hidden;
        max-width: 950px;
        margin: 0 auto;
        border: 1px solid #e6eaf0;
    }
    .edit-card-header {
        background: linear-gradient(90deg, #1e9fff 0%, #4facfe 100%);
        padding: 22px 32px;
        color: #fff;
        font-size: 20px;
        font-weight: 600;
        letter-spacing: 1px;
        border-bottom: 1px solid #e6eaf0;
    }
    .edit-card-body {
        padding: 32px 32px 24px 32px;
    }
    .form-section {
        border-bottom: 1px solid #f0f2f5;
        padding-bottom: 18px;
        margin-bottom: 24px;
    }
    .section-title {
        font-size: 18px;
        font-weight: 600;
        color: #1e9fff;
        margin-bottom: 18px;
        letter-spacing: 0.5px;
    }
    .layui-form-label {
        font-weight: 500;
        color: #333;
        font-size: 15px;
        padding: 0 10px 0 0;
        width: 110px;
        background: none;
    }
    .layui-input, .layui-textarea, .layui-select {
        border-radius: 6px !important;
        border: 1px solid #e6eaf0;
        font-size: 15px;
        background: #f9fbfd;
        transition: border-color 0.2s;
    }
    .layui-input:focus, .layui-textarea:focus, .layui-select:focus {
        border-color: #1e9fff;
        background: #fff;
    }
    .layui-form-item {
        margin-bottom: 18px;
    }
    .form-actions {
        padding: 24px 0 0 0;
        text-align: center;
        border-top: 1px solid #f0f2f5;
        margin-top: 32px;
    }
    .form-actions .layui-btn {
        padding: 0 38px;
        border-radius: 8px;
        font-weight: 600;
        font-size: 16px;
        margin: 0 10px;
        box-shadow: 0 2px 8px rgba(30,159,255,0.08);
    }
    .form-actions .layui-btn-primary {
        background: #f4f6fa;
        color: #1e9fff;
        border: 1px solid #1e9fff;
    }
    .required::before {
        content: "* ";
        color: #ff4d4f;
    }
    /* 产品明细表格美化 */
    .layui-table {
        border-radius: 8px;
        overflow: hidden;
        border: 1px solid #e6eaf0;
        background: #fff;
    }
    .layui-table thead tr {
        background: linear-gradient(90deg, #e3f2fd 0%, #f4f6fa 100%);
    }
    .layui-table th, .layui-table td {
        font-size: 15px;
        color: #333;
        padding: 10px 8px;
        border-color: #e6eaf0;
    }
    .layui-table th {
        font-weight: 600;
        color: #1e9fff;
        background: #f4f6fa;
    }
    .layui-btn-group {
        margin-bottom: 12px;
    }
    .layui-btn-sm {
        border-radius: 6px !important;
        font-size: 14px !important;
        padding: 0 16px !important;
    }
    /* 产品明细弹窗美化 */
    #addProductDialog .layui-form-label {
        width: 90px;
        color: #1e9fff;
        font-weight: 500;
    }
    #addProductDialog .layui-input-inline {
        width: 180px !important;
    }
    #addProductDialog .layui-form-mid {
        padding-left: 8px;
    }
    /* 响应式优化 */
    @@media (max-width: 1000px) {
        .edit-card {
            max-width: 100%;
            margin: 0 8px;
        }
        .edit-card-body {
            padding: 18px 6px 12px 6px;
        }
    }
</style>

<div class="edit-container">
    <div class="edit-card">
        <div class="edit-card-header">
            <i class="layui-icon layui-icon-form"></i> @ViewData["Title"]
        </div>
        <div class="edit-card-body">
            <form class="layui-form" lay-filter="salesOrderForm" id="salesOrderForm">
                <!-- 隐藏字段，存储ID用于区分新增/编辑 -->
                <input type="hidden" name="id" value="@Model.Id" />
                
                <!-- 基本信息区域 -->
                <div class="form-section">
                    <h3 class="section-title">基本信息</h3>
                    
                    <div class="layui-row layui-col-space20">
                        <div class="layui-col-md6">
                            <div class="layui-form-item">
                                <label class="layui-form-label required">订单编码</label>
                                <div class="layui-input-block">
                                    <input type="text" name="dOrderCode" value="@Model.DOrderCode" 
                                           lay-verify="required" placeholder="请输入订单编码" 
                                           autocomplete="off" class="layui-input" lay-verType="tips" />
                                </div>
                            </div>
                        </div>
                        <div class="layui-col-md6">
                            <div class="layui-form-item">
                                <label class="layui-form-label">订单名称</label>
                                <div class="layui-input-block">
                                    <input type="text" name="dOrderName" value="@Model.DOrderName" 
                                           placeholder="请输入订单名称" 
                                           autocomplete="off" class="layui-input" />
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="layui-row layui-col-space20">
                        <div class="layui-col-md6">
                            <div class="layui-form-item">
                                <label class="layui-form-label">客户编码</label>
                                <div class="layui-input-block">
                                    <input type="text" name="dCustomerCode" value="@Model.DCustomerCode" 
                                           placeholder="请输入客户编码" autocomplete="off" class="layui-input" />
                                </div>
                            </div>
                        </div>
                        <div class="layui-col-md6">
                            <div class="layui-form-item">
                                <label class="layui-form-label required">客户名称</label>
                                <div class="layui-input-block">
                                    <input type="text" name="dCustomerName" value="@Model.DCustomerName" 
                                           lay-verify="required" placeholder="请输入客户名称" 
                                           autocomplete="off" class="layui-input" lay-verType="tips" />
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="layui-row layui-col-space20">
                        <div class="layui-col-md6">
                            <div class="layui-form-item">
                                <label class="layui-form-label">客户PO号</label>
                                <div class="layui-input-block">
                                    <input type="text" name="dCustomerPONumber" value="@Model.DCustomerPONumber" 
                                           placeholder="请输入客户PO号" autocomplete="off" class="layui-input" />
                                </div>
                            </div>
                        </div>
                        <div class="layui-col-md6">
                            <div class="layui-form-item">
                                <label class="layui-form-label">订单类别</label>
                                <div class="layui-input-block">
                                    <select name="dOrderCategory">
                                        <option value="">请选择订单类别</option>
                                        <option value="客户订单" @(Model.DOrderCategory == "客户订单" ? "selected" : "")>客户订单</option>
                                        <option value="备货订单" @(Model.DOrderCategory == "备货订单" ? "selected" : "")>备货订单</option>
                                        <option value="单据" @(Model.DOrderCategory == "单据" ? "selected" : "")>单据</option>
                                        <option value="生产中" @(Model.DOrderCategory == "生产中" ? "selected" : "")>生产中</option>
                                        <option value="已完成" @(Model.DOrderCategory == "已完成" ? "selected" : "")>已完成</option>
                                        <option value="已确认" @(Model.DOrderCategory == "已确认" ? "selected" : "")>已确认</option>
                                        <option value="已发货" @(Model.DOrderCategory == "已发货" ? "selected" : "")>已发货</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="layui-row layui-col-space20">
                        <div class="layui-col-md6">
                            <div class="layui-form-item">
                                <label class="layui-form-label">质量要求</label>
                                <div class="layui-input-block">
                                    <select name="dQualityRequirement">
                                        <option value="">请选择质量要求</option>
                                        <option value="AAA" @(Model.DQualityRequirement == "AAA" ? "selected" : "")>AAA</option>
                                        <option value="AA" @(Model.DQualityRequirement == "AA" ? "selected" : "")>AA</option>
                                        <option value="A" @(Model.DQualityRequirement == "A" ? "selected" : "")>A</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                        <div class="layui-col-md6">
                            <!-- 空列，保持布局平衡 -->
                        </div>
                    </div>
                </div>
                
                <!-- 日期及财务信息区域 -->
                <div class="form-section">
                    <h3 class="section-title">时间与财务信息</h3>
                    
                    <div class="layui-row layui-col-space20">
                        <div class="layui-col-md6">
                            <div class="layui-form-item">
                                <label class="layui-form-label required">订货日期</label>
                                <div class="layui-input-block">
                                    <input type="text" name="dOrderDate" id="orderDate" 
                                           value="@(Model.DOrderDate.ToString("yyyy-MM-dd"))" 
                                           lay-verify="required" placeholder="请选择订货日期" 
                                           autocomplete="off" class="layui-input" lay-verType="tips" />
                                </div>
                            </div>
                        </div>
                        <div class="layui-col-md6">
                            <div class="layui-form-item">
                                <label class="layui-form-label">交货日期</label>
                                <div class="layui-input-block">
                                    <input type="text" name="deliveryDate" id="deliveryDate" 
                                           value="@Model.DeliveryDate" 
                                           placeholder="请选择交货日期" autocomplete="off" class="layui-input" />
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="layui-row layui-col-space20">
                        <div class="layui-col-md6">
                            <div class="layui-form-item">
                                <label class="layui-form-label">币别</label>
                                <div class="layui-input-block">
                                    <select name="dCurrency">
                                        <option value="">请选择币别</option>
                                        <option value="CNY" @(Model.DCurrency == "CNY" ? "selected" : "")>人民币(CNY)</option>
                                        <option value="USD" @(Model.DCurrency == "USD" ? "selected" : "")>美元(USD)</option>
                                        <option value="EUR" @(Model.DCurrency == "EUR" ? "selected" : "")>欧元(EUR)</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                        <div class="layui-col-md6">
                            <div class="layui-form-item">
                                <label class="layui-form-label">结账方式</label>
                                <div class="layui-input-block">
                                    <select name="dSettlementMethod">
                                        <option value="">请选择结账方式</option>
                                        <option value="现款现结" @(Model.DSettlementMethod == "现款现结" ? "selected" : "")>现款现结</option>
                                        <option value="月结30天" @(Model.DSettlementMethod == "月结30天" ? "selected" : "")>月结30天</option>
                                        <option value="月结60天" @(Model.DSettlementMethod == "月结60天" ? "selected" : "")>月结60天</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- 跟单信息区域 -->
                <div class="form-section">
                    <h3 class="section-title">跟单信息</h3>
                    
                    <div class="layui-row layui-col-space20">
                        <div class="layui-col-md6">
                            <div class="layui-form-item">
                                <label class="layui-form-label">跟单人员</label>
                                <div class="layui-input-block">
                                    <input type="text" name="dOrderFollower" value="@Model.DOrderFollower" 
                                           placeholder="请输入跟单人员" autocomplete="off" class="layui-input" />
                                </div>
                            </div>
                        </div>
                        <div class="layui-col-md6">
                            <div class="layui-form-item">
                                <label class="layui-form-label">业务员</label>
                                <div class="layui-input-block">
                                    <input type="text" name="dSalesperson" value="@Model.DSalesperson" 
                                           placeholder="请输入业务员" autocomplete="off" class="layui-input" />
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- 备注区域 -->
                <div class="form-section">
                    <h3 class="section-title">其他信息</h3>
                    
                    <div class="layui-form-item">
                        <label class="layui-form-label">备注</label>
                        <div class="layui-input-block">
                            <textarea name="dRemarks" placeholder="请输入备注" class="layui-textarea">@Model.DRemarks</textarea>
                        </div>
                    </div>
                </div>
                
                <!-- 产品明细区域 -->
                <div class="form-section">
                    <h3 class="section-title">产品明细信息</h3>
                    
                    <div class="layui-btn-group" style="margin-bottom: 10px;">
                        <button type="button" class="layui-btn layui-btn-sm" id="addProductBtn">
                            <i class="layui-icon layui-icon-add-1"></i> 添加产品
                        </button>
                        <button type="button" class="layui-btn layui-btn-sm layui-btn-danger" id="deleteProductBtn">
                            <i class="layui-icon layui-icon-delete"></i> 删除
                        </button>
                    </div>
                    
                    <div class="layui-table-body">
                        <table class="layui-table" id="productTable" lay-filter="productTable">
                            <thead>
                                <tr>
                                    <th style="width: 40px;"><input type="checkbox" lay-filter="productCheckAll" lay-skin="primary"></th>
                                    <th style="width: 60px;">序号</th>
                                    <th>产品编码</th>
                                    <th>产品名称</th>
                                    <th>规格</th>
                                    <th>材质</th>
                                    <th>颜色</th>
                                    <th>订货数量</th>
                                    <th>单位</th>
                                    <th>单价</th>
                                    <th>金额</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody id="productTableBody">
                                <!-- 产品明细列表将通过JavaScript动态添加 -->
                            </tbody>
                        </table>
                    </div>
                </div>
                
                <!-- 操作按钮区域 -->
                <div class="form-actions">
                    <button class="layui-btn layui-btn-normal" lay-submit lay-filter="saveBtn">保存</button>
                    <button type="button" class="layui-btn layui-btn-primary" id="cancelBtn">取消</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- 添加产品明细对话框 -->
<div id="addProductDialog" style="display: none; padding: 20px;">
    <form class="layui-form" id="productForm" lay-filter="productForm">
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">产品编码</label>
                <div class="layui-input-inline" style="width: 200px;">
                    <input type="text" name="productCode" id="productCode" placeholder="请选择产品" autocomplete="off" class="layui-input" readonly>
                </div>
                <div class="layui-form-mid">
                    <button type="button" class="layui-btn layui-btn-primary layui-btn-sm" id="selectProductBtn">
                        <i class="layui-icon layui-icon-search"></i>
                    </button>
                </div>
            </div>
        </div>
        
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">产品名称</label>
                <div class="layui-input-inline" style="width: 300px;">
                    <input type="text" name="productName" placeholder="产品名称" autocomplete="off" class="layui-input" readonly>
                </div>
            </div>
        </div>
        
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">规格</label>
                <div class="layui-input-inline">
                    <input type="text" name="specification" placeholder="规格" autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label">材质</label>
                <div class="layui-input-inline">
                    <input type="text" name="material" placeholder="材质" autocomplete="off" class="layui-input">
                </div>
            </div>
        </div>
        
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">颜色</label>
                <div class="layui-input-inline">
                    <select name="color" id="productColor">
                        <option value="">请选择颜色</option>
                        <option value="红色">红色</option>
                        <option value="蓝色">蓝色</option>
                        <option value="绿色">绿色</option>
                        <option value="黄色">黄色</option>
                        <option value="黑色">黑色</option>
                        <option value="白色">白色</option>
                        <option value="其他">其他</option>
                    </select>
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label">订货数量</label>
                <div class="layui-input-inline">
                    <input type="number" name="quantity" placeholder="订货数量" autocomplete="off" class="layui-input" lay-verify="required|number" value="1" min="1">
                </div>
            </div>
        </div>
        
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">单位</label>
                <div class="layui-input-inline">
                    <select name="unit" id="productUnit">
                        <option value="">请选择单位</option>
                        <option value="个">个</option>
                        <option value="件">件</option>
                        <option value="套">套</option>
                        <option value="kg">kg</option>
                        <option value="吨">吨</option>
                        <option value="米">米</option>
                    </select>
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label">单价</label>
                <div class="layui-input-inline">
                    <input type="number" name="price" placeholder="单价" autocomplete="off" class="layui-input" lay-verify="required|number" step="0.01" min="0">
                </div>
            </div>
        </div>
    </form>
</div>

<script>
layui.use(['form', 'layer', 'laydate'], function() {
    var form = layui.form,
        layer = layui.layer,
        laydate = layui.laydate,
        $ = layui.jquery;
    
    // 初始化日期选择器
    laydate.render({
        elem: '#orderDate',
        trigger: 'click'
    });
    
    laydate.render({
        elem: '#deliveryDate',
        trigger: 'click'
    });
    
    // 页面加载时的初始化
    $(document).ready(function(){
        var orderId = $('input[name="id"]').val();
        console.log('当前订单ID:', orderId);
        
        // 如果是编辑模式，加载产品明细数据
        if(orderId && parseInt(orderId) > 0){
            loadOrderDetails(orderId);
        }
    });
    
    // 加载订单详细信息
    function loadOrderDetails(orderId) {
        console.log('开始加载订单详细信息，订单ID:', orderId);
        layer.load(1, {shade: [0.3, '#fff']});
        
        $.ajax({
            url: '/OrderManagement/SalesOrder/GetById/' + orderId,
            type: 'GET',
            success: function(res) {
                layer.closeAll('loading');
                console.log('AJAX请求成功，完整响应数据:', res);
                console.log('响应数据类型:', typeof res);
                console.log('响应代码:', res.code);
                console.log('响应消息:', res.msg);
                
                if (res.code === 0 && res.data) {
                    console.log('订单数据:', res.data);
                    console.log('产品明细数据:', res.data.products);
                    console.log('产品明细数据类型:', typeof res.data.products);
                    console.log('产品明细是否为数组:', Array.isArray(res.data.products));
                    
                    // 检查是否有产品明细数据
                    if (res.data.products && Array.isArray(res.data.products) && res.data.products.length > 0) {
                        console.log('发现产品明细数据，数量:', res.data.products.length);
                        
                        // 清空现有的产品明细表格
                        $('#productTableBody').empty();
                        console.log('已清空产品明细表格');
                        
                        // 将产品明细数据添加到表格中
                        res.data.products.forEach(function(product, index) {
                            console.log('处理第', index + 1, '条产品明细:', product);
                            
                            var productData = {
                                productCode: product.ProductCode || product.productCode || '',
                                productName: product.ProductName || product.productName || '',
                                specification: product.Specification || product.specification || '',
                                material: product.Material || product.material || '',
                                color: product.Color || product.color || '',
                                quantity: product.Quantity || product.quantity || 0,
                                unit: product.Unit || product.unit || '',
                                price: product.Price || product.price || 0,
                                amount: product.Amount || product.amount || 0
                            };
                            
                            console.log('转换后的产品数据:', productData);
                            addProductToTable(productData, index + 1);
                        });
                        
                        // 重新渲染表单元素
                        form.render();
                        console.log('成功加载', res.data.products.length, '条产品明细数据');
                        layer.msg('成功加载 ' + res.data.products.length + ' 条产品明细', {icon: 1, time: 2000});
                    } else {
                        console.log('订单中没有产品明细数据');
                        console.log('products值:', res.data.products);
                        layer.msg('该订单暂无产品明细数据', {icon: 0, time: 2000});
                    }
                } else {
                    console.error('获取订单数据失败:', res.msg);
                    layer.msg(res.msg || '获取订单数据失败', {icon: 2});
                }
            },
            error: function(xhr, status, error) {
                layer.closeAll('loading');
                console.error('AJAX请求失败:', {xhr: xhr, status: status, error: error});
                console.error('响应文本:', xhr.responseText);
                layer.msg('获取订单数据失败: ' + error, {icon: 2});
            }
        });
    }
    
    // 添加产品到表格
    function addProductToTable(product, rowNumber) {
        console.log('添加产品到表格:', product);
        
        var rowHtml = '<tr>' +
            '<td><input type="checkbox" lay-skin="primary" lay-filter="productCheck"></td>' +
            '<td>' + rowNumber + '</td>' +
            '<td><input type="hidden" name="productCode" value="' + (product.productCode || '') + '">' + (product.productCode || '') + '</td>' +
            '<td><input type="hidden" name="productName" value="' + (product.productName || '') + '">' + (product.productName || '') + '</td>' +
            '<td><input type="hidden" name="specification" value="' + (product.specification || '') + '">' + (product.specification || '') + '</td>' +
            '<td><input type="hidden" name="material" value="' + (product.material || '') + '">' + (product.material || '') + '</td>' +
            '<td><input type="hidden" name="color" value="' + (product.color || '') + '">' + (product.color || '') + '</td>' +
            '<td><input type="hidden" name="quantity" value="' + (product.quantity || 0) + '">' + (product.quantity || 0) + '</td>' +
            '<td><input type="hidden" name="unit" value="' + (product.unit || '') + '">' + (product.unit || '') + '</td>' +
            '<td><input type="hidden" name="price" value="' + (product.price || 0) + '">' + (product.price || 0) + '</td>' +
            '<td><input type="hidden" name="amount" value="' + (product.amount || 0) + '">' + (product.amount || 0) + '</td>' +
            '<td>' +
                '<button type="button" class="layui-btn layui-btn-xs layui-btn-danger delete-product">' +
                    '<i class="layui-icon layui-icon-delete"></i>' +
                '</button>' +
            '</td>' +
        '</tr>';
        
        $('#productTableBody').append(rowHtml);
        form.render('checkbox');
    }
    
    // 添加产品按钮点击事件
    $('#addProductBtn').on('click', function(){
        layer.open({
            type: 1,
            title: '添加产品明细',
            area: ['600px', '500px'],
            content: $('#addProductDialog'),
            btn: ['确定', '取消'],
            yes: function(index, layero){
                var productData = form.val('productForm');
                
                if(!productData.productCode || !productData.quantity || !productData.price){
                    layer.msg('请填写完整的产品信息', {icon: 0});
                    return;
                }
                
                // 计算金额
                var amount = (parseFloat(productData.quantity) * parseFloat(productData.price)).toFixed(2);
                productData.amount = amount;
                
                // 获取当前行数
                var rowCount = $('#productTableBody tr').length + 1;
                
                // 添加到表格
                addProductToTable(productData, rowCount);
                
                // 清空表单
                document.getElementById('productForm').reset();
                form.render();
                
                layer.close(index);
            }
        });
    });
    
    // 删除产品按钮事件
    $(document).on('click', '.delete-product', function(){
        var $row = $(this).closest('tr');
        layer.confirm('确认要删除这条产品明细吗？', {icon: 3, title:'提示'}, function(index){
            $row.remove();
            // 重新编号
            $('#productTableBody tr').each(function(i){
                $(this).find('td:eq(1)').text(i + 1);
            });
            layer.close(index);
        });
    });
    
    // 批量删除产品按钮事件
    $('#deleteProductBtn').on('click', function(){
        var $checkedRows = $('#productTableBody input[type="checkbox"]:checked').closest('tr');
        if($checkedRows.length === 0){
            layer.msg('请至少选择一条记录', {icon: 0});
            return;
        }
        
        layer.confirm('确认要删除选中的 ' + $checkedRows.length + ' 条产品明细吗？', {icon: 3, title:'提示'}, function(index){
            $checkedRows.remove();
            // 重新编号
            $('#productTableBody tr').each(function(i){
                $(this).find('td:eq(1)').text(i + 1);
            });
            layer.close(index);
        });
    });
    
    // 表单提交事件
    form.on('submit(saveBtn)', function(data){
        var formData = data.field;
        var products = [];
        
        // 收集产品明细数据
        $('#productTableBody tr').each(function(){
            var $row = $(this);
            products.push({
                productCode: $row.find('[name="productCode"]').val(),
                productName: $row.find('[name="productName"]').val(),
                specification: $row.find('[name="specification"]').val(),
                material: $row.find('[name="material"]').val(),
                color: $row.find('[name="color"]').val(),
                quantity: parseFloat($row.find('[name="quantity"]').val()) || 0,
                unit: $row.find('[name="unit"]').val(),
                price: parseFloat($row.find('[name="price"]').val()) || 0,
                amount: parseFloat($row.find('[name="amount"]').val()) || 0
            });
        });
        
        // 添加产品明细到提交数据
        formData.products = products;
        
        console.log('提交的数据:', formData);
        
        // 显示加载层
        var loadIndex = layer.load(1, {shade: [0.3, '#fff']});
        
        // 提交数据
        $.ajax({
            url: formData.id > 0 ? '/OrderManagement/SalesOrder/Update' : '/OrderManagement/SalesOrder/Add',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(formData),
            success: function(res){
                layer.close(loadIndex);
                if(res.code === 0){
                    layer.msg('保存成功', {icon: 1, time: 1000}, function(){
                        window.location.href = '/OrderManagement/SalesOrder';
                    });
                } else {
                    layer.msg(res.msg || '保存失败', {icon: 2});
                }
            },
            error: function(xhr, status, error){
                layer.close(loadIndex);
                console.error('保存失败:', error);
                layer.msg('保存失败: ' + error, {icon: 2});
            }
        });
        
        return false;
    });
    
    // 表单输入检查
    $('input[name="dOrderCode"]').on('blur', function() {
        var orderCode = $(this).val();
        if (!orderCode) return;
        
        var id = $('input[name="id"]').val();
        
        // 检查编码是否已存在
        $.get('/OrderManagement/SalesOrder/CheckOrderCode', { 
            orderCode: orderCode, 
            id: id > 0 ? id : null 
        }, function(res) {
            if (res.exists) {
                layer.msg('该订单编码已存在，请修改', {icon: 2});
                $('input[name="dOrderCode"]').focus();
            }
        });
    });
    
    // 选择产品按钮点击事件
    $('#selectProductBtn').on('click', function(){
        // 此处应打开产品选择对话框，实际实现需要根据系统中的产品管理功能来完成
        // 简化示例：直接设置一些测试数据
        layer.msg('这里应弹出产品选择窗口，目前使用模拟数据', {icon: 0});
        
        setTimeout(function(){
            // 模拟选中了一个产品
            form.val('productForm', {
                'productCode': 'P001',
                'productName': '测试产品',
                'specification': '标准型',
                'material': '铝合金',
                'color': '蓝色',
                'unit': '个',
                'price': '100.00'
            });
            form.render('select');
        }, 500);
    });
    
    // 取消按钮事件
    $('#cancelBtn').on('click', function() {
        layer.confirm('确定放弃当前编辑？', {icon: 3, title: '确认'}, function(index) {
            window.location.href = '/OrderManagement/SalesOrder';
            layer.close(index);
        });
    });
});
</script> 